package cn.com.hhrcw.wx.util;

import cn.com.hhrcw.entity.MemberThird;
import cn.com.hhrcw.service.IMemberThirdService;
import cn.com.hhrcw.utils.Constant;
import cn.com.hhrcw.wx.params.TemplateParam;
import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.URLUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.jeecg.common.api.vo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

/**
 * @author lixingxing
 */
@Component
@Slf4j
public class WxTemplateUtil {
    @Autowired
    private WxConfig wxConfig;

    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private IMemberThirdService memberThirdService;

    /**
     * 测试用
     *
     * @param tplId
     * @return
     */
    @Deprecated
    public void sendTemplate(String tplId, String openid) {

        this.sendTemplate(openid, "面试通知", "保洁", "网裕科技", "求职中", "----------");
    }

    /**
     * @param newsType   "1".equals(newsType)) {//在线面试通知 线下面试通知
     * @param receiverId
     * @param title
     * @param job
     * @param entName
     * @param remark
     */
    public void sendTemplateByReceiveId(final String newsType, String receiverId, String title, String job, String entName, String remark) {

        try {
            log.info("准备发送模板消息{},{},{},{},{}", receiverId, title, job, entName, remark);
            LambdaUpdateWrapper<MemberThird> wrapper = Wrappers.lambdaUpdate();
            wrapper.eq(MemberThird::getUserId, receiverId).eq(MemberThird::getThirdType, Constant.THIRD_TYPE_WX_OA);
            MemberThird memberThird = memberThirdService.getOne(wrapper);
            if (null == memberThird) {
                log.info("未绑定用户{}", receiverId);
                return;
            }

            // 标记 oFNel6FxmRnq0fx1RRDdp0isycMo
            String openid = memberThird.getThirdSecondKey();
            log.info("发送模板消息openid:{} ", openid);

            String state = null;
            switch (newsType) {
                case "1":
                    state = "面试";
                    break;
                case "2":
                    state = "入职";
                    break;
                case "8":
                    state = "面试未通过";
                    break;
                case "9":
                    state = "面试通过";
                    break;
                case "11":
                    state = "面试";
                    break;
                case "12":
                    state = "面试";
                    break;
                default:
                    state = "求职";
                    break;
            }
            this.sendTemplate(openid, title, job, entName, state, remark);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }

    public void sendTemplate(String openid, String title, String job, String entName, String state, String remark) {
        String url = URLUtil.normalize(this.wxConfig.getWeione_url() + "/wxinterface/v3/send_template.thtml");
        log.info("weione_url:" + url);
        ThreadUtil.execute(() -> {
            String tpl = "{\n" +
                "           \"touser\":\"OPENID\",\n" +
                "           \"template_id\":\"H_jWFaXZ-S5zySh_aa-ZP_vkZYDkTSqMgultuEqoRb0\",\n" +
                "           \"url\":\"{url}\",  \n" +
                "           \"data\":{\n" +
                "                   \"first\": {\n" +
                "                       \"value\":\"{first}\",\n" +
                "                       \"color\":\"#173177\"\n" +
                "                   },\n" +
                "                   \"keyword1\":{\n" +
                "                       \"value\":\"{keyword1}\",\n" +
                "                       \"color\":\"#173177\"\n" +
                "                   },\n" +
                "                   \"keyword2\": {\n" +
                "                       \"value\":\"{keyword2}\",\n" +
                "                       \"color\":\"#173177\"\n" +
                "                   },\n" +
                "                   \"keyword3\": {\n" +
                "                       \"value\":\"{keyword3}\",\n" +
                "                       \"color\":\"#173177\"\n" +
                "                   },\n" +
                "                   \"remark\":{\n" +
                "                       \"value\":\"{remark}\",\n" +
                "                       \"color\":\"#173177\"\n" +
                "                   }\n" +
                "           }\n" +
                "       }";
            //https://developers.weixin.qq.com/doc/offiaccount/Message_Management/Template_Message_Interface.html#5
            tpl = tpl.replace("OPENID", openid);
            tpl = tpl.replace("{first}", title);
            tpl = tpl.replace("{keyword1}", job);
            tpl = tpl.replace("{keyword2}", entName);
            tpl = tpl.replace("{keyword3}", state);//求助状态

            tpl = tpl.replace("{remark}", remark);
            tpl = tpl.replace("{url}", "");

            TemplateParam p = new TemplateParam();
            p.setWxid(wxConfig.getWxid());
            p.setTimestamp(System.currentTimeMillis() + "");
            p.setTemplateJson(tpl);

            String sig = DigestUtils.md5Hex(p.getTimestamp()
                + wxConfig.getKey() + p.getWxid());
            p.setSig(sig);

            Result<?> r = restTemplate.postForObject(url, p, Result.class);
            log.info("weione_Result:" + r);
        });
    }

}
